package com.fc.push.mqtt.pool;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;

import com.fc.push.exception.MServerException;

import redis.clients.jedis.JedisPoolConfig;

public class MqttClientPool extends Pool<MqttClient> {
	
	public MqttClientPool(final GenericObjectPoolConfig poolConfig, final MqttClientFactory factory) {
		super(poolConfig, factory);
	}

	public MqttClientPool(final GenericObjectPoolConfig poolConfig, String serverURI, MqttConnectOptions options) {
		super(poolConfig, new MqttClientFactory(serverURI, options));
	}

	public MqttClient getResource() {
		return super.getResource();
	}

	public void returnResource(final MqttClient resource) {
		if (resource != null) {
			try {
				returnResourceObject(resource);
			} catch (Exception e) {
				try {
					resource.disconnect();
					resource.close();
				} catch (MqttException e1) {
					throw new MServerException(e, "Could not return the resource to the pool");
				}
			}
		}
	}
	
	public static void main(String[] args){
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		jedisPoolConfig.setMaxTotal(10);
		jedisPoolConfig.setMaxIdle(10);
		jedisPoolConfig.setMinIdle(10);
		jedisPoolConfig.setMaxWaitMillis(5000);
		jedisPoolConfig.setTestOnBorrow(true);
		jedisPoolConfig.setTestWhileIdle(true);
		jedisPoolConfig.setTestOnCreate(true);
		jedisPoolConfig.setTestOnReturn(true);
		
		MqttConnectOptions options = new MqttConnectOptions();
		options.setCleanSession(true);
		options.setConnectionTimeout(10);
		options.setKeepAliveInterval(20);
		
		MqttClientPool pool = new MqttClientPool(jedisPoolConfig, "tcp://112.74.101.75:1883", options);
		MqttClient client = pool.getResource();
		System.out.println(client.getServerURI());
		System.out.println(pool.getNumActive());
		
		pool.returnResource(client);
		System.out.println(pool.getNumActive());
		
		pool.close();
	}
}
